package com.jn.book.interceptor;

import androidx.annotation.NonNull;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class FormParamsInterceptor implements Interceptor {
    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request originalRequest = chain.request();

        // 仅对POST表单请求生效（Content-Type为application/x-www-form-urlencoded）
        if (originalRequest.method().equals("POST")
                && originalRequest.body() instanceof FormBody) {

            // 1. 转换为FormBody
            FormBody originalBody = (FormBody) originalRequest.body();

            // 2. 构建新的FormBody，添加全局参数
            FormBody.Builder newBodyBuilder = new FormBody.Builder();

            // 先添加原始参数
            for (int i = 0; i < originalBody.size(); i++) {
                newBodyBuilder.add(originalBody.name(i), originalBody.value(i));
            }

            // 再添加全局参数
            newBodyBuilder.add("channel", "official") // 渠道号
                    .add("version", "1.0.0"); // 版本号

            // 3. 构建新请求
            Request newRequest = originalRequest.newBuilder()
                    .post(newBodyBuilder.build())
                    .build();

            return chain.proceed(newRequest);
        }

        // 非表单请求直接放行
        return chain.proceed(originalRequest);
    }
}